package com.demo.activity;

import java.util.Calendar;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.ConvertUtils;

import com.xsq.BaseActivity;
import com.xsq.Constant;
import com.xsq.R;
import com.xsq.URLConstant;
import com.xsq.activity.DeviceSetActivity;
import com.xsq.util.HttpInterface;
import com.xsq.util.ServerUtils;

public class TestActivity  extends BaseActivity {


	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.consume_main);

	
		
		preferences = getSharedPreferences(Constant.CACHE_XSQ_POS, MODE_PRIVATE);
		editor = preferences.edit();

		serverUtils = new ServerUtils(preferences, editor);
		hi = new HttpInterface(serverUtils);

		myWebView = (WebView) findViewById(R.id.webview);

		WebSettings webSettings = myWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setSupportZoom(false); // 支持缩放
		webSettings.setBuiltInZoomControls(false); // 显示放大缩小

		webSettings.setDefaultTextEncodingName("utf-8");
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 解决缓存问题
		myWebView.addJavascriptInterface(new DeviceOp(this), "appControl");
		myWebView.setWebViewClient(new MyWebViewClient());
		myWebView.setWebChromeClient(new MyWebChromeClient());

		myWebView.loadUrl(URLConstant.PAGE_TEST);
	
		myWebView.setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {
					// 表示按返回键// 时的操作
					if (keyCode == KeyEvent.KEYCODE_BACK) {

						if (myWebView.canGoBack()) {
							myWebView.goBack(); // 后退
						} else {
							goBack();

						}
						// webview.goForward();//前进
						return true; // 已处理
					}
				}
				return false;
			}
		});
	}

	

	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
			AlertDialog.Builder b2 = new AlertDialog.Builder(TestActivity.this).setTitle("提示：").setMessage(message)
					.setPositiveButton("ok", new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					});
			b2.setCancelable(false);
			b2.create();
			b2.show();
			return true;
		}
	}

	private class MyWebViewClient extends WebViewClient {
		/**
		 * 如果希望点击链接由自己处理，而不是新开Android的系统browser中响应该链接。
		 * 给WebView添加一个事件监听对象（WebViewClient)并重写其中的一些方法：
		 * shouldOverrideUrlLoading：对网页中超链接按钮的响应。当按下某个连接时
		 * WebViewClient会调用这个方法，并传递参数：按下的url。比如当webview内嵌
		 * 网页的某个数字被点击时，它会自动认为这是一个电话请求，会传递url：tel:123,
		 * 如果你不希望如此可通过重写shouldOverrideUrlLoading函数解决
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// 当开启新的页面的时候用webview来进行处理而不是用系统自带的浏览器处理
			// 互联网用：webView.loadUrl("http://www.google.com");
			// 本地文件用：webView.loadUrl("file:///android_asset/XX.html"); 本地文件存放
			view.loadUrl(url);
			return true;
		}

		/**
		 * 载入页面完成的事件
		 **/
		@Override
		public void onPageFinished(WebView view, String url) {
			// 获取网页内容
			// view.loadUrl("javascript:window.local_obj.showSource"+
			// "('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
			super.onPageFinished(view, url);
			

			
		}

		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			// 这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
			Toast.makeText(getApplicationContext(), "加载失败,请联系管理员", Toast.LENGTH_LONG).show();
		}
	}

	
	private static final int GO_HOME = 1000;
	private static final int SHOW_SRCH_RESULT = 1001;
	
	
	private static final int SHOW_DAY_PICKER = 1002;
	private static final int SET_CONTROL_VALUE = 2001;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GO_HOME:
				goBack();
				break;	
			case SHOW_SRCH_RESULT:
				showSrchMsg(msg);
				break;	
			case SHOW_DAY_PICKER:
				showYearMonthDay(msg.getData().getString("id"),msg.getData().getString("ctype"));
				break;	
			case SET_CONTROL_VALUE:
				setControlValue(msg.getData().getString("id"),msg.getData().getString("value"));
				break;		
				
				
				
			}
		}
	};

	public void setControlValue(String id,String value){
		
		String call = "javascript:setControlValue('"+id+"','"+value+"');";
		
		myWebView.loadUrl(call);
	}
	
	public void showYearMonthDay(final String id,final String ctype){
		
		
		Calendar calendar = Calendar.getInstance();
		int C_YEAR = calendar.get(Calendar.YEAR);
		int C_MONTH = calendar.get(Calendar.MONTH);
		int C_DAY = calendar.get(Calendar.DAY_OF_MONTH);
		
		if (ctype.equals("1")) {
			final DatePicker picker = new DatePicker(this);
			picker.setCanceledOnTouchOutside(true);
			picker.setUseWeight(true);
			picker.setTopPadding(ConvertUtils.toPx(this, 10));
			picker.setRangeEnd(2020, 1, 1);
			picker.setRangeStart(2016, 1, 1);
			picker.setSelectedItem(C_YEAR, C_MONTH+1, C_DAY);

			picker.setResetWhileWheel(false);
			picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
				@Override
				public void onDatePicked(String year, String month, String day) {
					//Toast.makeText(getApplicationContext(), year + "-" + month + "-" + day, Toast.LENGTH_LONG).show();

					String value = year + "-" + month + "-" + day;
					Message message = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("id", id);
					bundle.putString("value", value);
					message.setData(bundle);
					message.what = SET_CONTROL_VALUE;
					mHandler.sendMessage(message);
					
				}
			});
			picker.setOnWheelListener(new DatePicker.OnWheelListener() {
				@Override
				public void onYearWheeled(int index, String year) {
					picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
				}

				@Override
				public void onMonthWheeled(int index, String month) {
					picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
				}

				@Override
				public void onDayWheeled(int index, String day) {
					picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
				}
			});
			picker.show();

		} else if (ctype.equals("2")) {

			DatePickerDialog dp = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
				public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
					int iyear = view.getYear();// 年
					String value = iyear + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
					

					Message message = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("id", id);
					bundle.putString("value", value);
					message.setData(bundle);
					message.what = SET_CONTROL_VALUE;
					mHandler.sendMessage(message);

				}
			}, C_YEAR, C_MONTH, C_DAY);// 初始年份,初始月份-1 ，初始日期
			dp.show();
		}
		 //日历控件
	}
	
	public void showSrchMsg(Message msg){
		
		hide_loading();
		String rs = msg.getData().getString("rs");
		String call = "javascript:showSrchRs('"+rs+"');";
		
		myWebView.loadUrl(call);
	}
	
	private void goBack() {
		Intent intent = new Intent(this, DeviceSetActivity.class);
		
		startActivity(intent);
		overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
	}

	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private class DeviceOp {

		private Context mContext;

		public DeviceOp(Context c) {
			mContext = c;
		}

		@JavascriptInterface
		public String doTest() {
			Toast.makeText(mContext, "test ... test", Toast.LENGTH_SHORT).show();
			return "1";
		}
		
		
		@JavascriptInterface
		public String goHome() {
			try{
				mHandler.sendEmptyMessage(GO_HOME);
				return "1";
			}catch(Exception e){
				return "-100";
			}
		}

		
		
		@JavascriptInterface
		public void showPicker(String id,String ctype){
			
			Message message = new Message();
			message.what = SHOW_DAY_PICKER;
			Bundle bundle = new Bundle();
			bundle.putString("id", id);
			bundle.putString("ctype", ctype);
			message.setData(bundle);
			
			mHandler.sendMessage(message);
		}
		
	

	}

}
